using AdminApiTemplate.Common.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace AdminApiTemplate.Api.Controllers.BaseControllers
{
    /// <summary>
    /// Token有效期即可访问的
    /// </summary>
    public class TokenRequiredController : Controller
    {
        /// <summary>
        /// 密钥
        /// </summary>
        public static readonly Dictionary<string, TokenUserItem> Secrets = new Dictionary<string, TokenUserItem>
        {
            { "8ufdvtf7hb4wzwlps5clf0ezwe1jvl2307g7s9vo2ie8cvuyxr",new TokenUserItem{ Id=1,ExpiredAt=new DateTime(2024,3,1)} }
        };

        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var sk = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (string.IsNullOrEmpty(sk))
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "Authorization必填");
            }

            if (!Secrets.ContainsKey(sk))
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "Authorization无效："+sk);
            }

            var ts = DateTime.Now - Secrets[sk].ExpiredAt;
            if (ts.TotalSeconds > 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "Token已失效，请更换Token或联系管理员延期Token");
            }

            UserId = Secrets[sk].Id;
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// 当前Token用户的Id
        /// </summary>
        public int UserId { get; set; } = 0;
    }

    public class TokenUserItem
    {
        public int Id { get; set; }

        public DateTime ExpiredAt { get; set; }
    }
}
